package com.instpower.things.handlers;

import com.instpower.things.config.CmdEnum;
import com.instpower.things.config.Configs;
import com.instpower.things.config.OtaStatus;
import com.instpower.things.entity.CabinetCmdLog;
import com.instpower.things.instpower.Connection;
import com.instpower.things.instpower.Handler;
import com.instpower.things.service.InstService;
import com.instpower.things.transport.DataBuffer;
import com.instpower.things.transport.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName Handler0F05Action
 * @Author: hellmash@gmail.com
 * @Date: 2020/5/24
 * @Version: 1.0.0
 * @Description: 更新指令反馈
 */
@Component(value = "CMD0F05")
public class Handler0F05Action extends Handler<Request> {

    @Autowired
    private InstService instService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public short getId() {
        return Configs.UPDATE_CMD;
    }

    @Override
    public void execute(Connection connection, Request request) throws UnsupportedEncodingException {
        String sn = request.getHeader().getAddr();
        logger.info("[{}]:Exec - CMD0F05 - BEGIN",sn);
        DataBuffer buffer = request.getData().encode();
        buffer.readBytes(8);
        //更新结果
        byte updateResult = buffer.readByte();

        //release after read
        buffer.release();

        OtaStatus status = OtaStatus.EXECUTE;
        CabinetCmdLog cmdLog = new CabinetCmdLog();
        cmdLog.setCabinetSn(sn);
        cmdLog.setCabinetCmd(CmdEnum.OTA);
        cmdLog.setCmdCode(String.format("0x%02x", Configs.UPDATE_CMD));
        if(0x00 == updateResult){
            status = OtaStatus.FINISH;
            cmdLog.setCabinetLog("机柜OTA升级成功!");
            instService.logCabinetCmd(cmdLog);
            logger.debug("[{}]升级成功",sn);
        }else if(0x01 == updateResult){
            logger.debug("[{}]正在升级",sn);
        }else{
            status = OtaStatus.FAIL;
            cmdLog.setCabinetLog("机柜OTA升级，参数错误!");
            instService.logCabinetCmd(cmdLog);
            logger.debug("参数错误");
        }
        Object taskId = redisTemplate.opsForHash().get(Configs.OTA_SINGLE_KEY, sn);
        if(null != taskId) {
            logger.debug("读取到缓存中的TASKID成功!升级机柜号:{}", taskId.toString());
            logger.debug("更新任务为{}",status.Val());
            //更新任务状态
            instService.updateCabinetOtaStatus(Integer.parseInt(taskId.toString()), status);
            //删除缓存
            redisTemplate.opsForHash().delete(Configs.OTA_SINGLE_KEY, sn);
        }
        logger.info("[{}]:Exec - CMD0F05 - END",sn);
    }
}
